<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTTP语音对话测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
        }
        .container {
            background: rgba(255, 255, 255, 0.1);
            padding: 20px;
            border-radius: 15px;
            backdrop-filter: blur(10px);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.05);
        }
        button {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 25px;
            cursor: pointer;
            margin: 5px;
            transition: all 0.3s;
        }
        button:hover:not(:disabled) {
            background: #5a67d8;
            transform: translateY(-2px);
        }
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        input {
            padding: 10px 15px;
            border: none;
            border-radius: 25px;
            margin: 5px;
            background: white;
            color: #333;
            outline: none;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 10px;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        .success {
            background: rgba(74, 222, 128, 0.2);
            border: 1px solid #4ade80;
        }
        .error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid #ef4444;
        }
        .info {
            background: rgba(59, 130, 246, 0.2);
            border: 1px solid #3b82f6;
        }
        .audio-controls {
            margin-top: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .record-btn {
            background: #ef4444;
            font-size: 18px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .record-btn.recording {
            animation: pulse 1s infinite;
        }
        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 HTTP语音对话测试</h1>
        <p>测试基于HTTP的语音对话功能，无需WebSocket连接</p>
        
        <div class="test-section">
            <h3>1. 服务健康检查</h3>
            <button onclick="testHealth()">检查服务状态</button>
            <div id="healthResult" class="result"></div>
        </div>

        <div class="test-section">
            <h3>2. 文本对话测试</h3>
            <input type="text" id="textInput" placeholder="输入测试文本" value="你好，我是谁？">
            <button onclick="testTextChat()">发送文本消息</button>
            <div id="textResult" class="result"></div>
            <div class="audio-controls">
                <button id="playTextAudio" onclick="playAudio('textAudio')" disabled>🔊 播放AI回复</button>
                <audio id="textAudio" controls style="display:none;"></audio>
            </div>
        </div>

        <div class="test-section">
            <h3>3. 语音对话测试</h3>
            <div class="audio-controls">
                <button class="record-btn" id="recordBtn" onclick="toggleRecording()">🎤</button>
                <span id="recordStatus">点击开始录音</span>
            </div>
            <div id="voiceResult" class="result"></div>
            <div class="audio-controls">
                <button id="playVoiceAudio" onclick="playAudio('voiceAudio')" disabled>🔊 播放AI回复</button>
                <audio id="voiceAudio" controls style="display:none;"></audio>
            </div>
        </div>

        <div class="test-section">
            <h3>4. 系统信息</h3>
            <div id="systemInfo" class="result info"></div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8123/api';
        let mediaRecorder = null;
        let audioChunks = [];
        let isRecording = false;
        let recordingStartTime = 0;

        // 初始化
        window.onload = function() {
            console.log('页面加载完成，开始初始化');
            updateSystemInfo();
            setTimeout(testHealth, 1000);
        };

        // 更新系统信息
        function updateSystemInfo() {
            const info = `浏览器: ${navigator.userAgent}
录音支持: ${navigator.mediaDevices ? '✅' : '❌'}
音频播放支持: ${window.Audio ? '✅' : '❌'}
当前时间: ${new Date().toLocaleString()}
API地址: ${API_BASE}`;
            
            document.getElementById('systemInfo').textContent = info;
        }

        // 测试健康检查
        async function testHealth() {
            const resultDiv = document.getElementById('healthResult');
            try {
                resultDiv.textContent = '正在检查服务状态...';
                resultDiv.className = 'result info';
                
                const response = await fetch(`${API_BASE}/chat/health`);
                const data = await response.json();
                
                console.log('健康检查响应:', data);
                
                if (data.code === 200) {
                    resultDiv.className = 'result success';
                    resultDiv.textContent = `✅ 服务正常
响应消息: ${data.message}
数据: ${data.data}
响应时间: ${data.timestamp}`;
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `❌ 服务异常
错误信息: ${data.message}`;
                }
            } catch (error) {
                resultDiv.className = 'result error';
                resultDiv.textContent = `❌ 连接失败: ${error.message}
请确保后端服务正在运行在 ${API_BASE}`;
            }
        }

        // 测试文本对话
        async function testTextChat() {
            const resultDiv = document.getElementById('textResult');
            const textInput = document.getElementById('textInput').value;
            
            if (!textInput.trim()) {
                resultDiv.className = 'result error';
                resultDiv.textContent = '请输入测试文本';
                return;
            }

            try {
                resultDiv.textContent = '正在处理文本消息...';
                resultDiv.className = 'result info';
                
                const requestData = {
                    textInput: textInput,
                    sessionId: 'test-' + Date.now()
                };

                console.log('发送文本请求:', requestData);
                const startTime = Date.now();

                const response = await fetch(`${API_BASE}/chat/voice`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestData)
                });

                const data = await response.json();
                const endTime = Date.now();
                console.log('文本对话响应:', data);

                if (data.code === 200 && data.data) {
                    const chatData = data.data;
                    resultDiv.className = 'result success';
                    resultDiv.textContent = `✅ 对话成功
用户输入: ${textInput}
识别结果: ${chatData.recognizedText}
AI回复: ${chatData.aiResponse}
处理时间: ${chatData.processingTime}ms
请求耗时: ${endTime - startTime}ms
音频数据: ${chatData.audioBase64 ? '已生成 (' + chatData.audioBase64.length + ' 字符)' : '无'}`;

                    // 处理音频播放
                    if (chatData.audioBase64) {
                        setupAudioPlayback('textAudio', chatData.audioBase64);
                        document.getElementById('playTextAudio').disabled = false;
                    }
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `❌ 对话失败
错误信息: ${data.message}
完整响应: ${JSON.stringify(data, null, 2)}`;
                }
            } catch (error) {
                resultDiv.className = 'result error';
                resultDiv.textContent = `❌ 请求失败: ${error.message}`;
            }
        }

        // 录音控制
        async function toggleRecording() {
            if (isRecording) {
                await stopRecording();
            } else {
                await startRecording();
            }
        }

        async function startRecording() {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];
                
                mediaRecorder.ondataavailable = (event) => {
                    audioChunks.push(event.data);
                };
                
                mediaRecorder.onstop = async () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    await processVoiceMessage(audioBlob);
                };
                
                mediaRecorder.start();
                isRecording = true;
                recordingStartTime = Date.now();
                
                document.getElementById('recordBtn').classList.add('recording');
                document.getElementById('recordStatus').textContent = '录音中... 点击停止';
                
                console.log('开始录音');
            } catch (error) {
                console.error('录音失败:', error);
                document.getElementById('voiceResult').className = 'result error';
                document.getElementById('voiceResult').textContent = '❌ 录音失败: ' + error.message;
            }
        }

        async function stopRecording() {
            if (mediaRecorder && isRecording) {
                mediaRecorder.stop();
                mediaRecorder.stream.getTracks().forEach(track => track.stop());
                isRecording = false;
                
                document.getElementById('recordBtn').classList.remove('recording');
                document.getElementById('recordStatus').textContent = '处理中...';
                
                const duration = Math.round((Date.now() - recordingStartTime) / 1000);
                console.log(`录音结束，时长: ${duration}秒`);
            }
        }

        // 处理语音消息
        async function processVoiceMessage(audioBlob) {
            const resultDiv = document.getElementById('voiceResult');
            
            try {
                // 转换为Base64
                const audioBase64 = await blobToBase64(audioBlob);
                const duration = Math.round((Date.now() - recordingStartTime) / 1000);
                
                resultDiv.textContent = `正在处理语音消息 (${duration}秒)...`;
                resultDiv.className = 'result info';
                
                const requestData = {
                    audioBase64: audioBase64,
                    sessionId: 'voice-test-' + Date.now()
                };

                console.log('发送语音请求，音频大小:', audioBase64.length);
                const startTime = Date.now();

                const response = await fetch(`${API_BASE}/chat/voice`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestData)
                });

                const data = await response.json();
                const endTime = Date.now();
                console.log('语音对话响应:', data);

                document.getElementById('recordStatus').textContent = '点击开始录音';

                if (data.code === 200 && data.data) {
                    const chatData = data.data;
                    resultDiv.className = 'result success';
                    resultDiv.textContent = `✅ 语音对话成功
录音时长: ${duration}秒
识别结果: ${chatData.recognizedText}
AI回复: ${chatData.aiResponse}
处理时间: ${chatData.processingTime}ms
请求耗时: ${endTime - startTime}ms
音频数据: ${chatData.audioBase64 ? '已生成 (' + chatData.audioBase64.length + ' 字符)' : '无'}`;

                    // 处理音频播放
                    if (chatData.audioBase64) {
                        setupAudioPlayback('voiceAudio', chatData.audioBase64);
                        document.getElementById('playVoiceAudio').disabled = false;
                    }
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `❌ 语音对话失败
错误信息: ${data.message}
完整响应: ${JSON.stringify(data, null, 2)}`;
                }
            } catch (error) {
                resultDiv.className = 'result error';
                resultDiv.textContent = `❌ 语音处理失败: ${error.message}`;
                document.getElementById('recordStatus').textContent = '点击开始录音';
            }
        }

        // 设置音频播放
        function setupAudioPlayback(audioId, audioBase64) {
            const audio = document.getElementById(audioId);
            const audioUrl = 'data:audio/wav;base64,' + audioBase64;
            audio.src = audioUrl;
            audio.style.display = 'block';
        }

        // 播放音频
        function playAudio(audioId) {
            const audio = document.getElementById(audioId);
            if (audio.src) {
                audio.play().catch(error => {
                    console.error('音频播放失败:', error);
                    alert('音频播放失败: ' + error.message);
                });
            }
        }

        // 工具函数
        function blobToBase64(blob) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => {
                    const result = reader.result;
                    const base64 = result.split(',')[1];
                    resolve(base64);
                };
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            });
        }
    </script>
</body>
</html>
